/**
 * 
 */
package ca.jerg.data;

import java.io.*;

public class ErgFileData implements IErgPoint
{
	public static final String HEADER = "[COURSE DATA]";
	public static final String FOOTER = "[END COURSE DATA]";
	
	public static void main( String[] args ) throws IOException
	{
		ErgFileHeader efh = new ErgFileHeader();
		ErgFileData efd = new ErgFileData();
		BufferedReader br = new BufferedReader(new FileReader("at-test.erg"));		
		
		// read the header
		if ( efh.read(br) != 0 )
		{
			System.err.println("Error reading header");
			return;
		}
		efh.write();
		
		// read the blank line between the header and the data
		br.readLine();
		
		// read the data
		if ( efd.read(br) != 0 )
		{
			System.err.println("Error reading data");
			return;
		}
		
		efd.write();	
		
		BufferedWriter bw = new BufferedWriter(new FileWriter("copy.erg"));
		efd.write(bw);
		bw.close();
	}
	
	private ErgData data;
	
	/**
	 * Create a blank .ERG file data set.
	 */	
	public ErgFileData()
	{
		data = new ErgData();
	}

	/**
	 * Return the data points that make up this .ERG data set
	 */
	public ErgData getData()
	{
		return data;
	}

	//@Override
	public int read( BufferedReader in )
	{
		try
		{
			// 1 - [COURSE DATA]
			if ( in.readLine().equals("[COURSE DATA]") == false )
			{
				System.err.println("course data");
				return 2;
			}				
			
			// 2 - data points
			if ( data.read(in) != 0 )
				return 2;			
		}
		catch ( IOException ioe )
		{
			return 1;
		}
	
		return 0;
	}

	/**
	 * 
	 * @param data 		the data set
	 */
	public void setData( ErgData data )
	{
		this.data = data;
	}

	//@Override
	public void write()
	{
		System.out.println();
		System.out.println(HEADER);
		data.write();
		System.out.println(FOOTER);
	}

	//@Override
	public boolean write( BufferedWriter out )
	{
		try
		{
			out.write(HEADER);
			out.newLine();
			data.write(out);
			out.write(FOOTER);
			out.newLine();
		}
		catch ( IOException ioe )
		{
			return false;
		}

		return true;		
	}
}
